<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr />
    <textarea
      name
      id
      cols="20"
      rows="10"
      placeholder="请输入内容（最多120字)"
      maxlength="120"
      v-model="commentmsg"
    ></textarea>
    <mt-button type="primary" size="large" @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, index) in commentList" :key="item.add_time">
        <div class="cmt-header">{{index}}楼，用户：{{item.user_name}}，时间：{{item.add_time | dataFormat}}</div>
        <div class="cmt-body">{{item.content == "" ? "此用户啥也没说":item.content}}</div>
      </div>
    </div>
    <mt-button size="large" @click="getMore">加载更多</mt-button>
  </div>
</template>

<style lang="scss">
.cmt-container {
  font-size: 14px;
  textarea {
    margin: 0;
    height: 111px;
  }
  .cmt-list {
    // margin-top: 5px;
    padding: 10px;
    .cmt-header {
      background-color: #ccc;
    }
    .cmt-body {
      padding: 10px 0;
    }
  }
}
</style>

<script>
import { Toast } from "mint-ui";
export default {
  // 把父组件的id拿过来
  props: ["id"],
  data() {
    return {
      pageIndex: 1, //默认展示第一页数据
      commentList: [], //评论数据
      commentmsg: ""
    };
  },
  methods: {
    getComment() {
      this.$http
        .get("getcomments/" + this.id + "?pageindex=" + this.pageIndex)
        .then(result => {
          if (result.body.status == 0) {
            //   每次获取新数据时应当让原来的数据拼接上现在的数据。concat为两个数组拼接语法
            this.commentList = this.commentList.concat(result.data.message);
          } else {
            Toast("获取评论失败");
          }
        });
    },
    getMore() {
      this.pageIndex++;
      this.getComment();
    },
    postComment() {
      if (this.commentmsg.trim() == "") {
        return Toast("评论内容不能为空！");
      }
      // this.$http.post("postcomment/"+ $route.params.id)明明父组件的id已经传过来了，为什么还要这样呢（狗头）
      this.$http
        .post("postcomment/" + this.id, { content: this.commentmsg.trim() })
        .then(function(result) {
          if (result.body.status == 0) {
            // 拼接一个评论对象
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.commentmsg.trim()
            };
            this.commentList.unshift(cmt);
            this.commentmsg = "";
          }
        });
    }
  },
  created() {
    this.getComment();
  }
};
</script>